package com.qyhl.webtv.module_live.teletext.newchatroom.roomutil;

import com.google.gson.Gson;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.basiclib.utils.network.model.ApiResult;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.entity.live.TeleTextMessageBean;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

public class NewChatRoomUtil extends WebSocketListener {
    private ChatRoomConnectListener listener;
    private String userName;
    private final String appId = "99d7b3fea998881f";
    private final String appKey = "86a94ebbac18ba8fad19c201";
    private String rid;
    private String nickName;
    private String logo;
    //连接状态
    private boolean isConnect = false;
    //重连
    private final int maxReconnect = 1;
    private int reconnectCount = 0;
    //加入聊天室标志
    private boolean isJoin = false;

    private OkHttpClient httpClient;

    private WebSocket webSocket;
    private Gson gson = new Gson();

    /**
     * 加入
     */
    public void join() {


        EasyHttp.post(CommonUtils.getInstance().getChatRoomUrl())
                .headers("X-CHAT-ID", appId)
                .headers("X-CHAT-KEY", appKey)
                .params("method", "joinRoom")
                .params("username", userName)
                .params("rid", rid)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        listener.connectFail();
                    }

                    @Override
                    public void onSuccess(String s) {
                        ApiResult apiResult = new Gson().fromJson(s,ApiResult.class);
                        if (apiResult.getCode() == 200) {
                            if ("success".equals(apiResult.getMessage())) {
                                isJoin = true;
                                connectChatRoomMessage();
                            } else {
                                listener.connectFail();
                            }
                        } else {
                            listener.connectFail();
                        }
                    }
                });

    }

    /**
     * 连接
     */
    private void connectChatRoomMessage() {
        httpClient = new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5, TimeUnit.SECONDS)
                .build();
        String socketUrl = CommonUtils.getInstance().getSocketUrl();
        Request request = new Request.Builder().url(socketUrl + appId + "/" + userName).build();
        httpClient.newWebSocket(request, this);
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        this.webSocket = webSocket;
        isConnect = true;
        reconnectCount = 0;
        sendInformation();
        listener.connect();
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        TeleTextMessageBean bean = gson.fromJson(text, TeleTextMessageBean.class);
        if (bean.getRid().equals(rid) && bean.getAction().equals("MSG")) {
            listener.message(bean);
        }
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        isConnect = false;
        if (isJoin) {
            if (reconnectCount < maxReconnect) {
                reconnectCount++;
                //重连
                reconnect();
            } else {
                //重连次数达到上限
                listener.connectFail();
            }
        }
    }

    /**
     * 断开连接
     */
    private void disconnection() {
        isConnect = false;
        if (webSocket != null) {
            webSocket.cancel();
            webSocket = null;
        }
        if (httpClient != null) {
            httpClient.dispatcher().executorService().shutdown();
            httpClient = null;
        }
    }

    /**
     * 重连
     */
    public void reconnect() {
        disconnection();
        connectChatRoomMessage();
    }

    /**
     * 退出聊天室
     */
    public void close() {
        isJoin = false;
        disconnection();

        EasyHttp.post(CommonUtils.getInstance().getChatRoomUrl())
                .headers("X-CHAT-ID", appId)
                .headers("X-CHAT-KEY", appKey)
                .params("method", "quitRoom")
                .params("username", userName)
                .params("rid", rid)
                .execute(new SimpleCallBack<String>() {

                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onSuccess(String s) {
                        ApiResult apiResult = new Gson().fromJson(s,ApiResult.class);
                        if (apiResult.getCode() == 200) {
                            if ("success".equals(apiResult.getMessage())) {
                            }
                        }
                    }
                });

    }

    /**
     * 发送配置信息
     */
    private void sendInformation() {
        if (isConnect && webSocket != null) {
            TeleTextMessageBean bean = new TeleTextMessageBean();
            bean.setAction("REPORT");
            bean.setLogo(logo);
            bean.setNickname(nickName);
            webSocket.send(gson.toJson(bean));
        }
    }

    /**
     * 发消息
     */
    public boolean send(String msg) {
        if (isConnect && webSocket != null) {
            TeleTextMessageBean bean = new TeleTextMessageBean();
            bean.setAction("MSG");
            bean.setRid(rid);
            bean.setMsgType("1");
            bean.setMessage(msg);
            return webSocket.send(gson.toJson(bean));
        } else {
            return false;
        }
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setRid(String rid) {
        this.rid = rid;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public void setLogo(String logo) {
        this.logo = logo;
    }

    public void setConnectListener(ChatRoomConnectListener listener) {
        this.listener = listener;
    }

    /**
     * 连接状态
     */
    public boolean isConnect() {
        return isConnect;
    }

    /**
     * 加入聊天室标志
     */
    public boolean isJoin() {
        return isJoin;
    }
}